package com.study.concurrent.B_ThreadSynchronizedBasic.c_UseIndependentAttributes;

/**
 * Created by 赵超 on 2017/3/22.
 */
public class Cinema {
    /**
     * 两个电影院的电影票数量
     */
    private long vacanciesCinema1;
    private long vacanciesCinema2;

    /**
     * 创建两个对象分别控制两个电影院的票务情况
     */
    private final Object controlCinema1, controlCinema2;

    public Cinema(long vacanciesCinema1, long vacanciesCinema2) {
        controlCinema1 = new Object();
        controlCinema2 = new Object();
        this.vacanciesCinema1 = vacanciesCinema1;
        this.vacanciesCinema1 = vacanciesCinema2;
    }

    /**
     * 电影院一 卖票方法
     * @param number
     * @return
     */
    public boolean sellTickets1(int number) {
        synchronized (controlCinema1) {
            if (number < vacanciesCinema1) {
                vacanciesCinema1 -= number;
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 电影院二 卖票方法
     * @param number
     * @return
     */
    public boolean sellTickets2(int number) {
        synchronized (controlCinema2) {
            if (number < vacanciesCinema2) {
                vacanciesCinema2 -= number;
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 电影院一 退票方法
     * @param number
     * @return
     */
    public boolean returnTickets1(int number) {
        synchronized (controlCinema1) {
            vacanciesCinema1 += number;
            return true;
        }
    }

    /**
     * 电影二 退票方法
     * @param number
     * @return
     */
    public boolean returnTickets2(int number) {
        synchronized (controlCinema2) {
            vacanciesCinema2 += number;
            return true;
        }
    }

    /**
     * 获取两个电影院各自剩余票数的方法
     * @return
     */
    public long getVacanciesCinema1() {
        return vacanciesCinema1;
    }

    public long getVacanciesCinema2() {
        return vacanciesCinema2;
    }
}
